<template>
  <TopMenu />
  <!-- 添加加载状态 -->
  <div class="loading-container" v-if="isLoading">
    <div class="loading-spinner">加载中...</div>
  </div>

  <div class="container" v-else-if="evtData && evtData.id">
    <div class="evtName" >{{ evtData.name }}</div>

    <!-- 步骤进度条 -->
    <div class="step-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
      </div>
      <div class="step-info">
        <span class="current-step">{{ currentStepText }}</span>
        <span class="progress-text">{{ progressText }}</span>
      </div>
    </div>

    <!-- 报名须知和赛事规章内容展示 -->
    <section class="evt-contents" v-if="currentStep === 1 && evtData.contents && evtData.contents.length > 0">
      <div class="content-navigation">
        <div class="nav-dots">
          <div
            v-for="(item, index) in evtData.contents"
            :key="index"
            class="nav-dot"
            :class="{ 'active': index === currentContentIndex }"
            @click="goToContent(index)"
          >
            <span class="dot-number">{{ index + 1 }}</span>
            <span class="dot-title">{{ item.themeTitle }}</span>
          </div>
        </div>
      </div>

      <div class="content-display">
        <div class="content-header">
          <h3 class="content-title">{{ currentContent.themeTitle }}</h3>
          <div class="content-counter">
            <span>{{ currentContentIndex + 1 }} / {{ evtData.contents?.length || 0 }}</span>
          </div>
        </div>

        <div class="content-body">
          <div class="content-text" v-html="currentContent.themeContent"></div>
        </div>
      </div>

      <div class="content-navigation-buttons">
        <button
          class="nav-btn prev-btn"
          :disabled="currentContentIndex === 0"
          @click="prevContent"
        >
          <svg class="btn-icon" viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" />
          </svg>
          上一项
        </button>
        <button
          class="nav-btn next-btn"
          :disabled="currentContentIndex === (evtData.contents?.length || 1) - 1"
          @click="nextContent"
        >
          下一项
          <svg class="btn-icon" viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
          </svg>
        </button>
      </div>
    </section>

    <!-- 无内容提示 -->
    <div class="no-content" v-else-if="currentStep === 1">
      <p>暂无报名须知内容</p>
    </div>

    <!-- 个人信息填写 -->
    <Information v-if="currentStep === 2" />

    <!-- 商品选择 -->
    <SelectGoods
      v-if="currentStep === 3"
      @update:selectedGoods="handleSelectedGoods"
    />

    <!-- 底部按钮组 -->
    <div class="btnGroups">
      <div class="btn" @click="goPre" v-if="currentStep > 1">上一步</div>
      <div
        class="btn"
        :class="{ 'active': !isRegistering, 'disabled': isRegistering }"
        @click="handleRegister"
      >
        {{ registerButtonText }}
      </div>
    </div>

    <!-- 报名成功弹窗 -->
    <div class="success-modal" v-if="showSuccessModal">
      <div class="modal-content">
        <div class="modal-header">
          <div class="success-icon">
            <svg viewBox="0 0 24 24" width="48" height="48">
              <path fill="currentColor" d="M9,20.42L2.79,14.21L5.62,11.38L9,14.77L18.88,4.88L21.71,7.71L9,20.42Z" />
            </svg>
          </div>
          <h3>报名成功！</h3>
        </div>
        <div class="modal-body">
          <p>恭喜您成功报名 {{ evtData.name }}</p>
          <div class="registration-info" v-if="selectedGoods.products.length > 0">
            <h4>已选商品：</h4>
            <div class="goods-list">
              <div v-for="product in selectedGoods.products" :key="product.productId" class="goods-item">
                <span>{{ product.productName }} x{{ product.quantity }}</span>
              </div>
            </div>
            <div class="total-amount">
              <strong>商品总计：¥{{ selectedGoods.totalPrice.toFixed(2) }}</strong>
            </div>
          </div>
          <p class="success-tip">请保持手机畅通，我们会及时与您联系</p>
        </div>
        <div class="modal-footer">
          <button class="modal-btn" @click="closeSuccessModal">确定</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 数据加载失败提示 -->
  <div class="error-container" v-else>
    <div class="error-message">
      <h3>数据加载失败</h3>
      <p>无法获取赛事信息，请稍后重试</p>
      <button class="retry-btn" @click="getEventData">重新加载</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import TopMenu from '@/components/TopMenu/index.vue'
import { useUserStore } from '@/stores/user/index.js'
import { useRouter, useRoute } from 'vue-router'
import Information from '@/views/user/information.vue'
import SelectGoods from './selectGoods.vue'
import { useEventStore } from '@/stores/event/index.js'
import { $message } from '@/utils/message.js'
import { createEvtOrder, eventData } from '@/api/data.js'

const eventStore = useEventStore()
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()

// 加载状态
const isLoading = ref(false)

// 当前步骤（1: 内容浏览, 2: 个人信息, 3: 商品选择）
const currentStep = ref(1)

// 内容浏览相关状态
const currentContentIndex = ref(0)

// 报名相关状态
const isRegistering = ref(false)
const isRegistered = ref(false)
const showSuccessModal = ref(false)
const selectedGoods = ref({ products: [], totalPrice: 0 })

// 获取赛事数据
const evtData = computed(() => {
  return eventStore.getEvtData
})

// 当前显示的内容
const currentContent = computed(() => {
  if (!evtData.value?.contents || evtData.value.contents.length === 0) {
    return { themeTitle: '', themeContent: '' }
  }
  return evtData.value.contents[currentContentIndex.value] || { themeTitle: '', themeContent: '' }
})

// 当前步骤文本
const currentStepText = computed(() => {
  if (currentStep.value === 1) {
    const totalContent = evtData.value?.contents?.length || 0
    if (totalContent === 0) {
      return '报名须知'
    }
    return `第 ${currentContentIndex.value + 1} 项内容`
  } else if (currentStep.value === 2) {
    return '个人信息填写'
  } else if (currentStep.value === 3) {
    return '选择商品'
  } else {
    return '完成报名'
  }
})

// 进度百分比
const progressPercentage = computed(() => {
  if (currentStep.value === 1) {
    const totalContent = evtData.value?.contents?.length || 1
    return ((currentContentIndex.value + 1) / totalContent) * 33 // 内容浏览占33%
  } else if (currentStep.value === 2) {
    return 66 // 个人信息填写阶段占66%
  } else if (currentStep.value === 3) {
    return 90 // 商品选择阶段占90%
  } else {
    return 100 // 完成
  }
})

// 进度文本
const progressText = computed(() => {
  if (currentStep.value === 1) {
    const totalContent = evtData.value?.contents?.length || 0
    return totalContent > 0 ? `共 ${totalContent} 项内容` : '报名须知'
  } else if (currentStep.value === 2) {
    return '填写个人信息'
  } else if (currentStep.value === 3) {
    return '选择商品（可选）'
  } else {
    return '报名完成'
  }
})

// 报名按钮文本
const registerButtonText = computed(() => {
  if (isRegistered.value) {
    return '已报名'
  } else if (isRegistering.value) {
    return '报名中...'
  } else if (currentStep.value === 1) {
    return '开始报名'
  } else if (currentStep.value === 2) {
    return '下一步'
  } else if (currentStep.value === 3) {
    return '确认报名'
  } else {
    return '完成报名'
  }
})

// 跳转到指定内容
const goToContent = (index) => {
  if (evtData.value?.contents && index >= 0 && index < evtData.value.contents.length) {
    currentContentIndex.value = index
  }
}

// 上一项内容
const prevContent = () => {
  if (currentContentIndex.value > 0) {
    currentContentIndex.value--
  }
}

// 下一项内容
const nextContent = () => {
  if (evtData.value?.contents && currentContentIndex.value < evtData.value.contents.length - 1) {
    currentContentIndex.value++
  }
}

// 处理选中商品数据
const handleSelectedGoods = (goodsData) => {
  selectedGoods.value = goodsData
}

// 下一步
const goNext = () => {
  if (currentStep.value < 3) {
    currentStep.value += 1
  }
}

// 上一步
const goPre = () => {
  if (currentStep.value > 1) {
    currentStep.value -= 1
  }
}

// 获取赛事数据
const getEventData = async () => {
  try {
    isLoading.value = true
    const eventId = route.query.evtId || 5
    const res = await eventData(eventId)

    if (res.code === 200) {
      eventStore.setCurrentEventData(res.data.evt)
      console.log('赛事数据加载成功:', res.data.evt)
    } else {
      $message.error(res.msg || '获取赛事信息失败')
    }
  } catch (error) {
    console.error('获取赛事数据失败:', error)
    $message.error('网络错误，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 处理报名
const handleRegister = async () => {
  if (isRegistered.value || isRegistering.value) {
    return
  }

  if (currentStep.value < 3) {
    goNext()
    return
  }

  // 开始报名流程
  isRegistering.value = true

  try {
    const registrationData = {
      evtId: evtData.value.id,
      skus: selectedGoods.value.products,
    }

    console.log('报名数据：', registrationData)
    const res = await createEvtOrder(registrationData)

    if (res.code === 200) {
      isRegistered.value = true
      showSuccessModal.value = true
    } else {
      $message.error(res.msg)
    }

  } catch (error) {
    console.error('报名失败：', error)
    $message.error(error.message || '报名失败，请重试')
  } finally {
    isRegistering.value = false
  }
}

// 关闭成功弹窗
const closeSuccessModal = () => {
  showSuccessModal.value = false
  router.push('/userCenter?type=signUp')
}

// 组件挂载
onMounted(async () => {
  // 页面滚动条置顶
  window.scrollTo(0, 0)

  // 检查用户登录状态
  if (!userStore.isSign) {
    router.push('/auth')
    return
  }

  // 检查是否已有赛事数据
  if (!evtData.value || !evtData.value.id) {
    console.log('未找到赛事数据，开始获取...')
    await getEventData()
  } else {
    console.log('已有赛事数据:', evtData.value)
  }
})
</script>

<style scoped lang="scss">
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.evtName {
  padding: 20px 0;
  font-size: 26px;
  font-weight: bold;
  text-align: center;
  color: #333;
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;

  .loading-spinner {
    font-size: 18px;
    color: #6b46c1;
    padding: 20px;
  }
}

// 错误状态样式
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;

  .error-message {
    text-align: center;
    padding: 40px;

    h3 {
      color: #dc3545;
      margin-bottom: 10px;
    }

    p {
      color: #666;
      margin-bottom: 20px;
    }

    .retry-btn {
      background: #6b46c1;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 6px;
      cursor: pointer;

      &:hover {
        background: #553c9a;
      }
    }
  }
}

// 无内容提示样式
.no-content {
  text-align: center;
  padding: 60px 20px;
  background: #f8f9fa;
  border-radius: 12px;
  margin-bottom: 30px;

  p {
    color: #666;
    font-size: 16px;
  }
}

// 步骤进度条
.step-progress {
  margin: 30px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;

  .progress-bar {
    width: 100%;
    height: 8px;
    background: #e9ecef;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 15px;

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #6b46c1, #8b5cf6);
      border-radius: 4px;
      transition: width 0.3s ease;
    }
  }

  .step-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #666;

    .current-step {
      font-weight: 600;
      color: #6b46c1;
      font-size: 16px;
    }

    .progress-text {
      color: #333;
      font-weight: 500;
    }
  }
}

// 内容展示区域
.evt-contents {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 30px;
}

// 内容导航
.content-navigation {
  background: #f8f9fa;
  padding: 20px;
  border-bottom: 1px solid #e9ecef;

  .nav-dots {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;

    .nav-dot {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      background: #fff;
      border: 2px solid #e9ecef;
      border-radius: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
      font-size: 14px;

      &:hover {
        border-color: #6b46c1;
        background: #f3f4f6;
      }

      &.active {
        background: #6b46c1;
        border-color: #6b46c1;
        color: #fff;
      }

      .dot-number {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 20px;
        height: 20px;
        background: #e9ecef;
        border-radius: 50%;
        font-size: 12px;
        font-weight: 600;
      }

      &.active .dot-number {
        background: rgba(255, 255, 255, 0.2);
        color: #fff;
      }

      .dot-title {
        font-weight: 500;
        max-width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

// 内容显示
.content-display {
  padding: 30px;

  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #e9ecef;

    .content-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }

    .content-counter {
      background: #6b46c1;
      color: #fff;
      padding: 6px 12px;
      border-radius: 15px;
      font-size: 14px;
      font-weight: 500;
    }
  }

  .content-body {
    .content-text {
      line-height: 1.8;
      color: #444;
      font-size: 16px;

      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        color: #333;
        margin: 20px 0 10px 0;
      }

      :deep(p) {
        margin: 10px 0;
      }

      :deep(ul), :deep(ol) {
        margin: 10px 0;
        padding-left: 20px;
      }

      :deep(li) {
        margin: 5px 0;
      }
    }
  }
}

// 内容导航按钮
.content-navigation-buttons {
  display: flex;
  justify-content: space-between;
  padding: 20px 30px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;

  .nav-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background: #fff;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    color: #333;
    transition: all 0.3s ease;

    &:hover:not(:disabled) {
      border-color: #6b46c1;
      color: #6b46c1;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    .btn-icon {
      fill: currentColor;
    }
  }
}

// 底部按钮组
.btnGroups {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;

  .btn {
    padding: 12px 30px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid #e9ecef;
    background: #fff;
    color: #666;

    &:hover {
      border-color: #6b46c1;
      color: #6b46c1;
    }

    &.active {
      background: #6b46c1;
      border-color: #6b46c1;
      color: #fff;

      &:hover {
        background: #553c9a;
        border-color: #553c9a;
      }
    }

    &.disabled {
      opacity: 0.6;
      cursor: not-allowed;
      background: #f8f9fa;
      border-color: #e9ecef;
      color: #999;

      &:hover {
        background: #f8f9fa;
        border-color: #e9ecef;
        color: #999;
      }
    }
  }
}

// 成功弹窗
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .modal-content {
    background: #fff;
    border-radius: 12px;
    padding: 0;
    max-width: 500px;
    width: 90%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);

    .modal-header {
      text-align: center;
      padding: 30px 30px 20px;
      border-bottom: 1px solid #e9ecef;

      .success-icon {
        margin-bottom: 15px;

        svg {
          fill: #28a745;
        }
      }

      h3 {
        margin: 0;
        color: #333;
        font-size: 24px;
      }
    }

    .modal-body {
      padding: 20px 30px;

      p {
        text-align: center;
        margin: 10px 0;
        color: #666;
        font-size: 16px;
      }

      .registration-info {
        margin: 20px 0;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 8px;

        h4 {
          margin: 0 0 10px 0;
          color: #333;
          font-size: 16px;
        }

        .goods-list {
          margin-bottom: 10px;

          .goods-item {
            padding: 5px 0;
            color: #666;
          }
        }

        .total-amount {
          text-align: right;
          color: #6b46c1;
          font-size: 18px;
        }
      }

      .success-tip {
        color: #28a745;
        font-weight: 500;
      }
    }

    .modal-footer {
      padding: 20px 30px 30px;
      text-align: center;

      .modal-btn {
        background: #6b46c1;
        color: #fff;
        border: none;
        padding: 12px 30px;
        border-radius: 8px;
        font-size: 16px;
        cursor: pointer;
        transition: background 0.3s ease;

        &:hover {
          background: #553c9a;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }

  .content-navigation .nav-dots {
    justify-content: flex-start;

    .nav-dot {
      .dot-title {
        max-width: 80px;
      }
    }
  }

  .content-display {
    padding: 20px;

    .content-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;

      .content-title {
        font-size: 20px;
      }
    }
  }

  .content-navigation-buttons {
    padding: 15px 20px;
  }

  .btnGroups {
    flex-direction: column;
    align-items: center;

    .btn {
      width: 200px;
      text-align: center;
    }
  }

  .success-modal .modal-content {
    margin: 20px;
    width: calc(100% - 40px);
  }
}
</style>
